using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;

namespace SmartLink.Repository
{
    public class PER_UserToRoleRepo : RepositoryBase<PER_UserToRole>, IPER_UserToRoleRepo
    {
        public void AllotRolesToUser(int userId, IList<int> roleIds)
        {
            using (DbTransaction tran = TranCreate())
            {
                try
                {
                    tran.Connection.Execute("DELETE FROM PER_UserToRole WHERE UserID=@UserID", new { UserID = userId }, tran);
                    foreach (var roleId in roleIds)
                    {
                        PER_UserToRole userToRole = new PER_UserToRole();
                        userToRole.UserID = userId;
                        userToRole.RID = roleId;
                        Add(userToRole, tran);
                    }
                    tran.Commit();
                }
                catch (Exception)
                {
                    TranRollback(tran);
                    throw;
                }
                finally
                {
                    TranClose(tran);
                }
            }
        }

        public bool AllotMenuIdToRole(IList<int> roleIds, IList<int> menuIds)
        {
            bool results = false;
            using (DbTransaction tran = this.TranCreate())
            {
                try
                {
                    foreach (int roleId in roleIds)
                    {
                        var repo = new RepositoryBase<PER_MenuPermissionsRole>();
                        repo.DeleteWhere(string.Format("delete from PER_MenuPermissionsRole where RID={0}", roleId), tran);
                        foreach (var menuId in menuIds)
                        {
                            PER_MenuPermissionsRole roleToMenu = new PER_MenuPermissionsRole();
                            roleToMenu.RID = roleId;
                            roleToMenu.MenuID = menuId;
                            repo.Add(roleToMenu, tran);
                        }
                    }
                    tran.Commit();
                    results = true;
                }
                catch (Exception ex)
                {
                    this.TranRollback(tran);
                    results = false;
                }
                finally
                {
                    this.TranClose(tran);
                }
            }
            return results;
        }


        public static IList<PER_UserToRole> GetAllUserToRoles()
        {
            IList<PER_UserToRole> results = new List<PER_UserToRole>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                results = conn.Query<PER_UserToRole>(" select *  from PER_UserToRole ").AsList();
                conn.Close();
            }
            return results;
        }

        public bool DeleteByUserId(int userId, DbTransaction tran = null)
        {
            bool result = false;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(" delete from PER_UserToRole where  userId=@userId");
                int count = conn.Execute(sql, new { userId = userId }, tran);
                if (count > 0)
                    result = true;
                conn.Close();
            }
            return result;
        }

        /// <summary>
        /// 获取角色关联的用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IList<PER_UserToRole> GetRoleUsers(int roleId)
        {
            IList<PER_UserToRole> results = new List<PER_UserToRole>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var paras = new { rid = roleId };
                results = conn.Query<PER_UserToRole>(" select *  from PER_UserToRole where rid=@rid", paras).AsList();
                conn.Close();
            }
            return results;
        }

        public IEnumerable<int> GetUserRoleIds(int userId)
        {
            var sql = "SELECT RID FROM PER_UserToRole WHERE UserID=@UserID";
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                return conn.Query<int>(sql, new { UserID = userId });
            }
        }

        public IEnumerable<PER_RoleGroup> GetUserRoles(int userId)
        {
            var sql = @"SELECT rg.* FROM PER_UserToRole uto
                                    JOIN PER_RoleGroup rg ON uto.RID=rg.ID
                                   WHERE uto.UserID=@UserId";
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                return conn.Query<PER_RoleGroup>(sql, new { UserId = userId });
            }
        }
    }
}
